<?php

class Install extends CFormModel
{
	const REQUIRED_NOT_FOUND  = 0;
	const REQUIRED_INSTALLED  = 1;
	const REQUIRED_EXISTS	  = 2;
	
	public function installCoreTables()
	{
		$sql = "DROP TABLE IF EXISTS {{modules}};";
		Yii::app()->db->createCommand($sql)->execute();
		$sql="
			CREATE TABLE IF NOT EXISTS {{modules}} (
			  `id` int(11) NOT NULL AUTO_INCREMENT,
			  `name` varchar(64) NOT NULL,
			  `title` varchar(255) NOT NULL,
			  `lang_module` tinyint(1) NOT NULL,
			  `seo_module` tinyint(1) NOT NULL,
			  PRIMARY KEY (`id`)
			) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
		Yii::app()->db->createCommand($sql)->execute();
		
		$sql = "DROP TABLE IF EXISTS {{sessions}};";
		Yii::app()->db->createCommand($sql)->execute();
		$sql="
			CREATE TABLE IF NOT EXISTS {{sessions}} (
			  `id` char(32) NOT NULL,
			  `expire` int(11) DEFAULT NULL,
			  `data` text,
			  PRIMARY KEY (`id`)
			) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
		Yii::app()->db->createCommand($sql)->execute();
	}
	
	public function checkDependencies($module, $modules)
	{
		$config = Install::getModuleInstaller($module)->config();
		if (empty($config['dependencies']))
		{
			return array('result'=>Install::REQUIRED_INSTALLED);
		}
		else
		{
			foreach ($config['dependencies'] as $key=>$value)
			{
				$moduleName = (is_array($value))?$key:$value;
				$res = Yii::app()->db->createCommand()
						->select('id')
						->from('{{modules}}')
						->where('name=:name', array(':name'=>$moduleName))
						->queryRow();
				if ($res)
				{
					$return['result'] = Install::REQUIRED_INSTALLED;
				}
				else
				{
					if (in_array($moduleName, $modules))
					{
						$return['result'] = Install::REQUIRED_EXISTS;
						return $return;
					}
					else
					{
						$return['result'] = Install::REQUIRED_NOT_FOUND;
						$return['required'][] = $moduleName;
						return $return;
					}
				}
			}
			return $return;
		}
	}
	
	public function updateModulesTable($config)
	{
		$sql = "INSERT INTO {{modules}} (name, title, lang_module, seo_module) VALUES (:name, :title, :lang_module, :seo_module)";
		$command = Yii::app()->db->createCommand($sql);
		$command->bindParam(":name", $config['name'], PDO::PARAM_STR);
		$command->bindParam(":title", $config['title'], PDO::PARAM_STR);
		if (isset($config['dependencies']['languages']))
		{
			$command->bindValue(":lang_module", 1, PDO::PARAM_INT);
		}
		else
		{
			$command->bindValue(":lang_module", 0, PDO::PARAM_INT);
		}
		if (isset($config['dependencies']['seo']))
		{
			$command->bindValue(":seo_module", 1, PDO::PARAM_INT);
		}
		else
		{
			$command->bindValue(":seo_module", 0, PDO::PARAM_INT);
		}
		$command->execute();
	}
	
	public static function getModuleInstaller($moduleName)
	{
		$class = ucfirst($moduleName).'Install';
		Yii::import('application.modules.'.$moduleName.'.install.'.$class);
		
		return new $class;
	}
}

?>
